package com.rpc.netty.simpleNetty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {


  /**
   * @param ctx 上下文对象：管道pipeline(管道里多个处理器)    channel通道      连接地址
   * @param msg 客户端发送的消息
   * @return void
   * @describe 读取客户端消息事件
   * @author 何章怀晓 hezhanghuaixiao
   * @date 2022/3/1  15:19
   * @other
   */
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    System.out.println("server" + ctx);

    ctx.channel().eventLoop().execute(new Runnable() {
      @Override
      public void run() {

      }
    });

    ByteBuf byteBuf = (ByteBuf) msg;
    System.out.println("msg:" + byteBuf.toString(CharsetUtil.UTF_8));

    System.out.println("客户端地址"+ctx.channel().remoteAddress());
  }
  //数据读取完毕回复客户端
  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    //数据写入缓冲区并刷新
    ctx.writeAndFlush(Unpooled.copiedBuffer("hello",CharsetUtil.UTF_8));
  }


  //处理异常,关闭通道

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
  }
}
